package com.hqyj.springCloudWeb.service.impl;

import com.hqyj.entity.account.User;
import com.hqyj.entity.common.ResultEntity;
import com.hqyj.springCloudWeb.service.AccountOpenFeignClient;
import com.hqyj.springCloudWeb.service.UserService;
import com.hqyj.springCloudWeb.util.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yun
 * @date 2021-5-13 18:01
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private AccountOpenFeignClient accountOpenFeignClient;

    @Override
    public ResultEntity<User> login(User user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUserName(), MD5Util.getMD5(user.getPassword()));
        usernamePasswordToken.setRememberMe(user.isRememberMe());

        try {
            subject.login(usernamePasswordToken);
            subject.checkRoles();

            Session session = subject.getSession();
            session.setAttribute("user", subject.getPrincipal());

        } catch (Exception e) {
            e.printStackTrace();

            return new ResultEntity<User>( ResultEntity.ResultStatus.FAILED.status,
                    "用户名或密码错误！");
        }

        return new ResultEntity<User>(ResultEntity.ResultStatus.SUCCESS.status,
                "登录成功！", user);
    }

    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

    @Override
    public ResultEntity<User> updateUser(User user) {
        List<User> users = accountOpenFeignClient.getUserByUserNameOrEmail(
                user.getUserName(), user.getEmail());
        if (users.stream().filter(item -> item.getId() != user.getId()).count() > 0) {
            return new ResultEntity<User>(ResultEntity.ResultStatus.FAILED.status, "用户名或邮箱已存在！");
        }

        accountOpenFeignClient.updateUserByUser(user);

        // 修改 Session 与 Principal
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user", user);
        PrincipalCollection oldPrincipal = subject.getPrincipals();
        String realmName = oldPrincipal.getRealmNames().iterator().next();
        SimplePrincipalCollection newPrincipal =
                new SimplePrincipalCollection(user, realmName);
        subject.runAs(newPrincipal);

        return new ResultEntity<User>(ResultEntity.ResultStatus.SUCCESS.status,
                "修改成功！", user);
    }
}
